using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.IO;


namespace DrawToolsLib
{
    /// <summary>
    /// Polyline tool
    /// </summary>
    class ToolPolyLine : ToolObject
    {
        private GraphicsPolyLine newPolyLine;

        public ToolPolyLine()
        {
            ToolCursor = Cursors.Arrow;
        }

        /// <summary>
        /// Create new object
        /// </summary>
        public override void OnMouseDown(DrawingCanvas drawingCanvas, MouseButtonEventArgs e)
        {
            Point p = e.GetPosition(drawingCanvas);

            if (newPolyLine == null)
            {
                newPolyLine = new GraphicsPolyLine(
                    new Point[] { p, p },
                    drawingCanvas.LineWidth,
                    drawingCanvas.ObjectColor,
                    drawingCanvas.ActualScale,
                    drawingCanvas.ActiveIcon.CoordinateSystem);

                AddNewObject(drawingCanvas, newPolyLine);
            }
            else
            {
                newPolyLine.AddPoint(p);
            }
        }

        /// <summary>
        /// Set cursor and resize new polyline
        /// </summary>
        public override void OnMouseMove(DrawingCanvas drawingCanvas, MouseEventArgs e)
        {
            drawingCanvas.Cursor = ToolCursor;

            if (newPolyLine == null)
            {
                return;
            }

            if (!drawingCanvas.IsMouseCaptured)
            {
                return;
            }
            
            Point p = e.GetPosition(drawingCanvas);
            newPolyLine.MoveHandleTo(p, newPolyLine.HandleCount);
        }

        /// <summary>
        /// Do nothing on mouse up, just override the base onmouseup.
        /// </summary>
        public override void OnMouseUp(DrawingCanvas drawingCanvas, MouseButtonEventArgs e)
        {
        }

        /// <summary>
        /// End the polyline using doubleclick.
        /// </summary>
        internal override void OnMouseDoubleClick(DrawingCanvas drawingCanvas, MouseButtonEventArgs e)
        {
            newPolyLine.RemoveLastPoint();
            newPolyLine = null;

            base.OnMouseUp(drawingCanvas, e);
            e.Handled = true;
        }
    }
}
